package com.sqx.modules.message.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Query;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserCertification;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserCertificationService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.taking.dao.OrderTakingDao;
import com.sqx.modules.taking.entity.Game;
import com.sqx.modules.taking.entity.OrderTaking;
import com.sqx.modules.task.dao.HelpOrderDao;
import com.sqx.modules.task.dao.HelpTakeDao;
import com.sqx.modules.task.entity.HelpOrder;
import com.sqx.modules.task.entity.HelpTake;
import com.sqx.modules.utils.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息
 */
@Service
public class MessageServiceImpl extends
        ServiceImpl<MessageInfoDao, MessageInfo> implements MessageService {

    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderTakingDao orderTakingDao;
    @Autowired
    private UserService userService;
    @Autowired
    private HelpOrderDao helpOrderDao;
    @Autowired
    private HelpTakeDao helpTakeDao;
    @Autowired
    private UserCertificationService userCertificationService;
    @Autowired
    private CommonInfoService commonInfoService;

    @Override
    public Result auditMessage(Long messageId, Integer status, String auditContent) {
        MessageInfo messageInfo = baseMapper.selectById(messageId);
        messageInfo.setStatus(status);
        UserEntity byId = userService.getById(messageInfo.getByUserId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (status == 2) {
            if (byId.getStatus().equals(1)) {
                //2封号
                byId.setStatus(2);
                userService.updateById(byId);
                if(messageInfo.getPlatform() == 3){
                    List<HelpOrder> helpOrders = helpOrderDao.selectList(new QueryWrapper<HelpOrder>().eq("user_id", byId.getUserId()).in("status", 2, 3));
                    for(HelpOrder helpOrder:helpOrders){
                        List<HelpTake> helpTakeList = helpTakeDao.selectList(new QueryWrapper<HelpTake>().eq("order_id", helpOrder.getId()));
                        for(HelpTake helpTake:helpTakeList){
                            helpTake.setStatus(4);
                            helpTakeDao.updateById(helpTake);
                            MessageInfo messageInfos = new MessageInfo();
                            messageInfos.setContent("订单："+helpOrder.getOrderNo()+"，账号存在违规，系统已封禁，任务自动下架！");
                            messageInfos.setTitle("任务下架通知");
                            messageInfos.setState(String.valueOf(6));
                            messageInfos.setUserName(byId.getUserName());
                            messageInfos.setUserId(String.valueOf(byId.getUserId()));
                            messageInfos.setCreateAt(sdf.format(new Date()));
                            messageInfos.setIsSee("0");
                            baseMapper.insert(messageInfos);
                        }
                        helpOrder.setStatus(5);
                        MessageInfo messageInfos = new MessageInfo();
                        messageInfos.setContent("当前账号存在违规行为，已被系统封禁，如有疑问，请联系客服！");
                        messageInfos.setTitle("账号封禁通知");
                        messageInfos.setState(String.valueOf(6));
                        messageInfos.setUserName(byId.getUserName());
                        messageInfos.setUserId(String.valueOf(byId.getUserId()));
                        messageInfos.setCreateAt(sdf.format(new Date()));
                        messageInfos.setIsSee("0");
                        baseMapper.insert(messageInfos);
                    }
                }else{
                    //任务下架
                    orderTakingDao.updateTakingStatusByUserId(byId.getUserId());
                    MessageInfo messageInfos = new MessageInfo();
                    messageInfos.setContent("当前账号存在违规行为，已被系统封禁，如有疑问，请联系客服！");
                    messageInfos.setTitle("账号封禁通知");
                    messageInfos.setState(String.valueOf(6));
                    messageInfos.setUserName(byId.getUserName());
                    messageInfos.setUserId(String.valueOf(byId.getUserId()));
                    messageInfos.setCreateAt(sdf.format(new Date()));
                    messageInfos.setIsSee("0");
                    baseMapper.insert(messageInfos);
                }


            }

        } else if (status == 3) {
            //3下架
            if (messageInfo.getPlatform() == 3) {
                List<HelpOrder> helpOrders = helpOrderDao.selectList(new QueryWrapper<HelpOrder>().eq("user_id", byId.getUserId()).in("status", 2, 3));
                for(HelpOrder helpOrder:helpOrders){
                    List<HelpTake> helpTakeList = helpTakeDao.selectList(new QueryWrapper<HelpTake>().eq("order_id", helpOrder.getId()));
                    for(HelpTake helpTake:helpTakeList){
                        helpTake.setStatus(4);
                        helpTakeDao.updateById(helpTake);
                        MessageInfo messageInfos = new MessageInfo();
                        messageInfos.setContent("订单："+helpOrder.getOrderNo()+"，任务存在违规，系统自动下架！");
                        messageInfos.setTitle("任务下架通知");
                        messageInfos.setState(String.valueOf(6));
                        messageInfos.setUserName(byId.getUserName());
                        messageInfos.setUserId(String.valueOf(byId.getUserId()));
                        messageInfos.setCreateAt(sdf.format(new Date()));
                        messageInfos.setIsSee("0");
                        baseMapper.insert(messageInfos);
                    }
                    helpOrder.setStatus(5);
                    MessageInfo messageInfos = new MessageInfo();
                    messageInfos.setContent("当前账号存在违规行为，已被系统封禁，如有疑问，请联系客服！");
                    messageInfos.setTitle("账号封禁通知");
                    messageInfos.setState(String.valueOf(6));
                    messageInfos.setUserName(byId.getUserName());
                    messageInfos.setUserId(String.valueOf(byId.getUserId()));
                    messageInfos.setCreateAt(sdf.format(new Date()));
                    messageInfos.setIsSee("0");
                    baseMapper.insert(messageInfos);
                }
            } else if (messageInfo.getPlatform() == 4) {
                OrderTaking orderTaking = orderTakingDao.selectById(messageInfo.getPlatformId());
                if (orderTaking != null) {
                    orderTaking.setStatus(2);
                    orderTakingDao.updateById(orderTaking);
                    byId = userService.getById(orderTaking.getUserId());
//                    orderTakingDao.deleteById(messageInfo.getPlatformId());
                    MessageInfo messageInfos = new MessageInfo();
                    String content = orderTaking.getGameId();
                    if (content.length() > 5) {
                        content = content.substring(0, 5) + "...";
                    }
                    messageInfos.setContent("您发布的服务：" + content + "，涉及违规，已做下架处理,如有疑问请联系客服！");
                    messageInfos.setTitle("接单下架通知");
                    messageInfos.setState(String.valueOf(6));
                    messageInfos.setUserName(byId.getUserName());
                    messageInfos.setUserId(String.valueOf(byId.getUserId()));
                    messageInfos.setCreateAt(sdf.format(new Date()));
                    messageInfos.setIsSee("0");
                    baseMapper.insert(messageInfos);
                }
            }
        }
        messageInfo.setAuditContent(auditContent);
        baseMapper.updateById(messageInfo);
        return Result.success();
    }

    @Override
    public PageUtils selectMessageList(Map<String, Object> params) {
        Long userId = (Long) params.get("userId");
        Integer state = (Integer) params.get("state");
        Integer type = (Integer) params.get("type");
        Integer status = (Integer) params.get("status");
        String platform = (String) params.get("platform");
        String userType = String.valueOf(params.get("userType"));
        IPage<MessageInfo> page = this.page(
                new Query<MessageInfo>().getPage(params),
                new QueryWrapper<MessageInfo>()
                        .eq(userId != null, "user_id", userId)
                        .eq(state != null, "state", state)
                        .eq(status != null, "status", status)
                        .in("1".equals(userType), "state", "4","5")
                        .in("2".equals(userType), "state", "8","6")
                        .in("3".equals(userType), "state", "9","7")
                        .eq(state!=null && (state==10 || state==11),"is_see","0")
                        .eq(StringUtils.isNotBlank(platform), "platform", platform)
                        .eq(type != null, "type", type).orderByDesc("create_at")
        );
        List<MessageInfo> records = page.getRecords();
        if (records.size() > 0) {
            for (MessageInfo messageInfo : records) {
                if (state != null && state == 9) {
                    if (StringUtils.isNotEmpty(messageInfo.getType())) {
                        Orders orders = ordersService.getById(Long.parseLong(messageInfo.getType()));
                        messageInfo.setOrders(orders);
                        if (orders != null) {
                            OrderTaking orderTaking = orderTakingDao.selectById(orders.getOrderTakingId());
                            messageInfo.setOrderTaking(orderTaking);
                        }
                    }
                }
                if (messageInfo.getUserId() != null) {
                    UserEntity user = userService.getById(messageInfo.getUserId());
                    messageInfo.setUserEntity(user);
                    if (user != null) {
                        messageInfo.setUserName(user.getUserName());
                    }
                }
                if (messageInfo.getByUserId() != null) {
                    UserEntity user = userService.getById(messageInfo.getByUserId());
                    if (user != null) {
                        messageInfo.setByUserName(user.getUserName());
                    }
                }

            }
        }

        return new PageUtils(page);
    }

    @Override
    public int saveBody(MessageInfo messageInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        messageInfo.setCreateAt(sdf.format(now));
        messageInfo.setStatus(0);
        return messageInfoDao.insert(messageInfo);
    }

    @Override
    public int update(MessageInfo messageInfo) {
        return messageInfoDao.updateById(messageInfo);
    }

    @Override
    public int delete(Long id) {
        return messageInfoDao.deleteById(id);
    }

    @Override
    public MessageInfo selectMessageById(Long id) {
        return messageInfoDao.selectById(id);
    }

    @Override
    public int updateSendState(Long userId, Integer state) {
        return messageInfoDao.updateSendState(userId, state);
    }

    @Override
    public Result selectMasterLocation(Integer page,Integer limit,String masterName,String phone,Long userId,String city){
        return Result.success().put("data",new PageUtils(baseMapper.selectMasterLocation(new Page<>(page,limit),masterName,phone,userId,city)));
    }


    @Override
    public Result insertMasterLocation(MessageInfo messageInfo){
        messageInfo.setState("12");
        UserCertification userCertification = userCertificationService.getOne(new QueryWrapper<UserCertification>().eq("user_id",Long.parseLong(messageInfo.getUserId())));
        if(userCertification!=null){
            if(StringUtils.isNotEmpty(messageInfo.getTypeId()) && StringUtils.isNotEmpty(messageInfo.getTypeName())){
                userCertification.setLongitude(messageInfo.getTypeId());
                userCertification.setLatitude(messageInfo.getTypeName());
                String way = commonInfoService.findOne(414).getValue();
                if("1".equals(way)){
                    CommonInfo one = commonInfoService.findOne(217);
                    String url = "https://apis.map.qq.com/ws/geocoder/v1/";
                    Map<String, String> maps = new HashMap<>();
                    maps.put("location", messageInfo.getTypeName() + "," + messageInfo.getTypeId());
                    maps.put("key", one.getValue());
                    String data = HttpClientUtil.doGet(url, maps);
                    JSONObject jsonObject = JSON.parseObject(data);
                    String status = jsonObject.getString("status");
                    if ("0".equals(status)) {
                        JSONObject result = jsonObject.getJSONObject("result");
                        String address = result.getString("address");
                        messageInfo.setContent(address);
                        userCertification.setNowAddress(address);
                        JSONObject adInfo = result.getJSONObject("ad_info");
                        userCertification.setCity(adInfo.getString("city"));
                    } else {
                        log.error("转换失败！！！原因:" + jsonObject.getString("message"));
                    }
                }else{
                    String value = commonInfoService.findOne(415).getValue();
                    String url="http://api.tianditu.gov.cn/geocoder";
                    Map<String,String> param=new HashMap<>();
                    JSONObject postStr=new JSONObject();
                    postStr.put("lon",messageInfo.getTypeId());
                    postStr.put("lat",messageInfo.getTypeName());
                    postStr.put("ver","1");
                    param.put("postStr",postStr.toJSONString());
                    param.put("type","geocode");
                    param.put("tk",value);
                    String s = HttpClientUtil.doGet(url,param);
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String status = jsonObject.getString("status");
                    if("0".equals(status)){
                        JSONObject result = jsonObject.getJSONObject("result");
                        String address = result.getString("formatted_address");
                        messageInfo.setContent(address);
                        userCertification.setNowAddress(address);
                        JSONObject addressComponent = result.getJSONObject("addressComponent");
                        String city = addressComponent.getString("city");
                        String province = addressComponent.getString("province");
                        if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(city)){
                            if("新疆维吾尔自治区".equals(province) || "台湾省".equals(province)){
                                city = addressComponent.getString("county");
                            }else{
                                city = addressComponent.getString("province");
                            }
                        }
                        userCertification.setCity(city);
                    }
                    log.error("转换失败！！！原因:" + jsonObject.getString("msg"));
                }

                userCertificationService.updateById(userCertification);
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                baseMapper.insert(messageInfo);
            }
        }
        return Result.success();
    }


}
